<template>
  <div>
    <!-- 头部 start -->
    <Header>
      <div
        slot="extra"
        style="display: flex;align-items: center;justify-content: center;"
      >
        {{ currentNav.label }}
      </div>
      <div slot="right-extra">
        <div class="search_wrp">
          <i
            @tap="goSearch"
            style="font-size: 18px;"
            class="jeicon jeicon-search je-audio-btn"
          />
          <i
            v-show="hasKeyword"
            class="Identification"
          />
        </div>
      </div>
    </Header>
    <!-- 头部 end -->
    <div class="transaction-wrp">
      <div class="mui-content">
        <div
          id="slider"
          class="mui-slider mui-fullscreen"
        >
          <!-- 一级tab start -->
          <div
            id="sliderSegmentedControl"
            class="mui-scroll-wrapper mui-slider-indicator mui-segmented-control mui-segmented-control-inverted"
          >
            <div class="mui-scroll page_nav">
              <a
                v-for="item in nav_list"
                :key="item.value"
                :class="{'mui-active': currentNav.value === item.value}"
                @tap="switchNav(item)"
                class="mui-control-item je-audio-btn"
              >
                {{ item.label }} ({{ item.count }})
              </a>
            </div>
          </div>
          <!-- 一级tab end -->
          <div
            class="mui-slider-group self-group"
          >
            <div
              v-for="list in nav_list"
              :id="list.value"
              :key="list.value"
              :class="{'mui-active': currentNav.value === list.value}"
              class="mui-control-content"
              style="border:0px;height: 100%;"
            >
              <div
                v-show="currentNav.value === 'task'"
                class="task_type mui-scroll-wrapper"
              >
                <div class="mui-scroll">
                  <div
                    v-for="item in taskTypeList"
                    :key="item.value"
                    @tap="changeType(item)"
                    :class="{active: item.value === currentTaskType}"
                    class="je-audio-btn"
                  >
                    {{ item.label }} <span v-if="item.value==='delay'">({{ delayCount }})</span>
                  </div>
                </div>
              </div>
              <div
                id="refreshContainer"
                :style="{top: currentNav.value === 'task' ? '50px' : ''}"
                class="mui-scroll-wrapper updown"
              >
                <div
                  class="mui-scroll"
                  style="background: #f8f8f8;"
                >
                  <div
                    v-if="list.dataList.length > 0"
                    class="items-wrp"
                  >
                    <list-items
                      v-for="item in list.dataList"
                      :key="item.JE_SYS_TASK_ID"
                      :item="item"
                      :type="currentNav"
                      v-on:changeStar="changeStar"
                    />
                  </div>
                  <p
                    v-else
                    class="no-data"
                  >
                    暂无数据
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <float-btn
        @tap="add"
        type="icon"
        text="jeicon-plus"
      />
    </div>
  </div>
</template>

<script>
import floatBtn from '@/components/floatbtn';
import Header from '@/components/header/index';


export default {
  name: 'Transaction',
  components: {
    floatBtn,
    Header,
  },
  data() {
    return {
      nav_list: [
        {
          label: '待我处理',
          value: 'task',
          color: '#7DBAFD',
          count: 0,
          dataList: [],
          start: 0,
          page: 1,
          refresh: 0,
        },
        {
          label: '我的安排',
          value: 'send',
          color: '#FD877D',
          count: 0,
          dataList: [],
          start: 0,
          page: 1,
          refresh: 1,
        },
        {
          label: '历史事务',
          value: 'history',
          color: '#CBA3F9',
          count: 0,
          dataList: [],
          start: 0,
          page: 1,
          refresh: 2,
        },
      ],
      taskTypeList: [
        {
          value: 'all',
          label: '全部',
        },
        {
          value: 'today',
          label: '今天',
        },
        {
          value: 'tomorrow',
          label: '明天',
        },
        {
          value: 'week',
          label: '本周',
        },
        {
          value: 'month',
          label: '本月',
        },
        {
          value: 'delay',
          label: '已延期',
        },
      ],
      currentNav: {
        label: '待我处理',
        value: sessionStorage.getItem('actionType') || 'task',
        color: '#536DFE',
        refresh: 0,
      },
      currentTaskType: 'all',
      delayCount: 0,
      currentWebObj: {},
      hasKeyword: '',
      pullrefreshlist: [],
    };
  },
  created() {
    this.initCount();
    JE.registBadge((badges, refreshList) => {
      if (refreshList.length == 0) return false;
      refreshList.forEach((item) => {
        if (item.code === 'JE-PLUGIN-TRANSACTION' && item.type === 'TRANSACTION') {
          this.initCount();
          this.initParams(this.currentNav.value);
          this.initParams(this.nav_list[0].value);
          this.initData();
        }
      });
    });
  },
  mounted() {
    const that = this;
    const nextpage = this.$route.query.type;
    if (nextpage === 'refreshList') {
      this.refreshList();
    } else if (nextpage === 'changeStatues') {
      this.changeStatues();
    } else if (nextpage === 'userInput') {
      this.userInput();
    } else {
      this.initData();
    }
    const data = this.nav_list.find(item => item.value === this.currentNav.value);
    this.switchNav(data);
    // 处理左右滑动
    document.querySelector('.mui-slider').addEventListener('slide', (event) => {
      this.currentNav = this.nav_list[event.detail.slideNumber];
      if (this.nav_list[event.detail.slideNumber].dataList.length < 1) {
        this.initData();
      }
    });
    mui('.mui-scroll-wrapper.task_type').scroll({
      scrollX: true,
      scrollY: true,
      indicators: false,
    });
    const pullRefreshWrapper = Array.from(document.querySelectorAll('.mui-scroll-wrapper.updown'));
    this.pullRefreshWrapper = pullRefreshWrapper.map(
      pullRefreshEl => mui(pullRefreshEl).pullRefresh4HTML({
        // 下拉刷新
        down: {
          callback() {
            const self = this;
            that.initParams(that.currentNav.value);
            that.initData((data) => {
              that.nav_list.forEach((item) => {
                if (item.value === that.currentNav.value) {
                  item.dataList = data.rows;
                  item.start = 10 * item.page;
                  item.page++;
                }
              });
              that.initCount();
              self.endPulldownToRefresh();
              JE.msg('刷新成功!');
              that.refreshUpRefresh(data.rows.length, self);
            });
          },
        },
        // 上拉加载
        up: {
          callback() {
            const self = this;
            that.initData((data) => {
              that.nav_list.forEach((item) => {
                if (item.value === that.currentNav.value) {
                  item.dataList = item.dataList.concat(data.rows);
                  item.start = 10 * item.page;
                  item.page++;
                }
              });
              that.initCount();
              self.endPullupToRefresh(false);
              that.refreshUpRefresh(data.rows.length, self);
              JE.msg(data.rows.length < 1 ? '已无更多数据!' : '加载成功!');
            });
          },
        },
      })
    );
    this.initParams(this.currentNav.value);
  },
  methods: {
    // 点击领取任务/完成任务点击后退刷新任务数量和待我处理，我的安排列表
    changeStatues() {
      this.initCount();
      this.initParams('task');
      this.initParams('send');
      // this.nav_list[1].dataList = [];
      this.initData();
    },
    refreshList() {
      this.initCount();
      this.initParams(this.currentNav.value);
      this.initParams(this.nav_list[0].value);
      // this.nav_list[0].dataList = [];
      this.initData();
    },
    userInput() {
      this.hasKeyword = this.$route.query.user_input;
      // console.log(this.hasKeyword)
      this.initParams(this.currentNav.value);
      this.initData();  
    },
    refreshUpRefresh(length, self) {
      if (length < 10) {
        return self.endPullupToRefresh(true);
      }
      return self.enablePullupToRefresh();
    },
    // 初始化查询条件,
    initParams(type) {
      this.nav_list.forEach((item) => {
        if (type === item.value) {
          item.dataList = [];
          item.start = 0;
          item.page = 1;
        }
      });
    },
    // 初始化列表
    async initData(fn) {
      if (this.loading) return;
      const userInfo = JE.getCurrentUser();
      let params = {};
      this.nav_list.forEach((item) => {
        if (item.value === this.currentNav.value) {
          params = {
            start: item.start,
            page: item.page,
            limit: 10,
          };
        }
      });
      if (this.currentNav.value === 'send') {
        params = Object.assign({}, params, {
          tableCode: 'JE_SYS_TASK',
          whereSql: ` AND SY_CREATEUSERID='${userInfo.id}'`,
          orderSql: ' order by SY_CREATETIME desc',
        });
      } else {
        params = Object.assign({}, params, {
          tableCode: 'JE_SYS_JOB_V',
          whereSql: ` AND SY_CREATEUSERID='${userInfo.id}' AND JOBMX_SFBJLS ${this.currentNav.value === 'history' ? "='1'" : "!='1'"}`,
          orderSql: ' order by JOBMX_JX desc,SY_CREATETIME desc',
        });
      }
      if (this.hasKeyword) {
        params.whereSql += ` AND TASK_BT LIKE '%${this.hasKeyword}%'`;
      }
      if (this.currentNav.value === 'task') {
        params.type = this.currentTaskType === 'all' ? '' : this.currentTaskType;
      }
      this.loading = true;
      JE.showWaiting();
      const data = await JE.ajax({ url: '/je/job/job/load', params, async: false });
      this.delayCount = data.delayCount;
      if (fn && typeof (fn) === 'function') {
        fn(data);
        this.loading = false;
        JE.closeWaiting();
        return;
      }

      this.nav_list.forEach((item) => {
        if (item.value === this.currentNav.value) {
          item.dataList = item.dataList.concat(data.rows);
          item.start = 10 * item.page;
          item.page++;
        }
      });
      this.loading = false;
      JE.closeWaiting();
      mui('.mui-scroll-wrapper.updown').scroll();
    },
    initCount() {
      JE.ajax({
        url: '/je/portal/portal/getPortalNum',
        params: { pushTypes: 'TRANSACTION' },
      }).then((data) => {
        this.nav_list.forEach((item) => {
          switch (item.value) {
            case 'task':
              item.count = data[0].numObj.taskCount;
              break;
            case 'send':
              item.count = data[0].numObj.ownerCount;
              break;
            case 'history':
              item.count = data[0].numObj.historyCount;
              break;
            default:
          }
        });
      });
    },
    switchNav(item) {
      // 清空用户输入
      // this.hasKeyword = '';
      // 切换主题颜色
      this.currentNav = {
        value: item.value,
        color: item.color,
        refresh: item.refresh,
        label: item.label,
      };
      sessionStorage.setItem('actionType', this.currentNav.value);
      this.initData();
    },
    add() {
      this.$router.push({
        path: '/JE-PLUGIN-TRANSACTION/addtransaction',
        query: {
          id: '__addTansactionView',
          title: '任务交办',
        },
      });
      // this.$router.push('/addtransaction')
      // JE.openWindow({
      //   url: './pages_addtransaction_index.html',
      //   id: '__addTansactionView',
      //   title: '任务交办',
      //   extras: {},
      //   hideNView: true,
      // });
    },
    changeStar(item) {
      const that = this;
      if (this.loading) return;
      this.loading = true;
      JE.ajax({
        url: `/je/job/job/${item.JOBMX_JX === '1' ? 'cancelStar' : 'addStar'}`,
        params: { JE_SYS_JOB_ID: item.JE_SYS_JOB_ID },
      }).then(() => {
        that.initParams(that.currentNav.value);
        that.loading = false;
        that.initData();
      }).catch(() => {
        that.loading = false;
      });
    },
    // 切换时间
    changeType(item) {
      this.currentTaskType = item.value;
      this.initParams(this.currentNav.value);
      this.initData();
    },
    goSearch() {
      this.$router.push({
        path: '/JE-PLUGIN-TRANSACTION/searchpage',
        query: {
          id: '__searchView',
          title: '查询',
          tabValue: this.currentNav.value,
          key: this.hasKeyword,
          hideNView: true,
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
  @import "~@/theme/index.less";
  .transaction-wrp {
    position: absolute;
    top: 44 * @hd;
    right: 0;
    bottom: 0;
    left: 0;
    background: #f8f8f8;
    p {
      margin: 0;
    }
    .page_nav {
      padding: 0 20px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      font-size: 13px;
      height: 44 * @hd;
      background: #ffffff;
      width: 100%;
      > a {
        color: #A9ABA9;
        border-bottom: 1px solid transparent;
        padding: 0 5px;
        height: 44 * @hd;
        line-height: 44 * @hd;
        &.mui-active {
          display: block !important;
          border-bottom: 1px solid #536DFE !important;
        }
      }
    }
    .task_type {
      height: 44 * @hd;
      line-height: 44 * @hd;
      background: #ffffff;
      width: 100%;
      overflow-x: scroll;
      overflow-y: hidden;
      .mui-scroll {
        height: 44 * @hd;
        width: auto;
        display: flex;
        align-content: center;
        justify-content: flex-start;
        overflow-x: scroll;
          > div {
          width: 80 * @hd;
          font-size: @font-size-subhead;
          color: @color-text-base;
          text-align: center;
          float: left;
          &.active {
            color: #536DFE;
          }
        }
        &:after {
          content: '';
          display: table;
          clear: both;
        }
      }
    }
    .updown {
      background: #f8f8f8;
      overflow: auto;
      top: 5px;
      &.task {
        top: 54 * @hd;
      }
      .items-wrp {
        padding: 0 10px;
        padding-bottom: 20px;
      }
      .no-data {
        margin-top: 50 * @hd;
        font-size: 18 * @hd;
        text-align: center;
      }
    }
  }
</style>
<style lang="less">
@import "~@/theme/index.less";
html,
body {
  background-color:#F8F8F8 !important;
}
.task_type::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
}
.mui-scroll::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
}
.mui-bar ~ .mui-content .mui-fullscreen {
  top: 44 * @hd;
  height: auto;
}
.mui-pull-top-tips {
  position: absolute;
  top: -20 * @hd;
  left: 50%;
  margin-left: -25 * @hd;
  width: 40 * @hd;
  height: 40 * @hd;
  border-radius: 100%;
  z-index: 1;
}
.mui-bar ~ .mui-pull-top-tips {
  top: 24 * @hd;
}
.mui-pull-top-wrapper {
  width: 42 * @hd;
  height: 42 * @hd;
  display: block;
  text-align: center;
  background-color: #efeff4;
  border: 1 * @hd solid #ddd;
  border-radius: 25 * @hd;
  background-clip: padding-box;
  box-shadow: 0 4 * @hd 10 * @hd #bbb;
  // overflow: hidden;
}
.mui-pull-top-tips.mui-transitioning {
  -webkit-transition-duration: 200ms;
  transition-duration: 200ms;
}
.mui-pull-top-tips .mui-pull-loading {
  /*-webkit-backface-visibility: hidden;
      -webkit-transition-duration: 400ms;
      transition-duration: 400ms;*/

  margin: 0;
}
.mui-pull-top-wrapper .mui-icon,
.mui-pull-top-wrapper .mui-spinner {
  margin-top: 7 * @hd;
}
.mui-pull-top-wrapper .mui-icon.mui-reverse {
  /*-webkit-transform: rotate(180deg) translateZ(0);*/
}
.mui-pull-bottom-tips {
  text-align: center;
  background-color: #efeff4;
  font-size: 15 * @hd;
  line-height: 40 * @hd;
  color: #777;
}
.mui-pull-top-canvas {
  overflow: hidden;
  background-color: #fafafa;
  border-radius: 40 * @hd;
  box-shadow: 0 4 * @hd 10 * @hd #bbb;
  width: 40 * @hd;
  height: 40 * @hd;
  margin: 0 auto;
}
.mui-pull-top-canvas canvas {
  width: 40 * @hd;
}
.mui-slider-indicator.mui-segmented-control {
  .mui-scroll-wrapper {
    height: 44 * @hd;
  }
  height: 45 * @hd;
  background-color: #ffffff;
}

.mui-pull-bottom-wrapper {
  background: #f8f8f8;
}

.mui-scrollbar {
  display: none !important;
}
.mui-fullscreen .mui-segmented-control~.mui-slider-group {
  top: 49 * @hd;
}
.search_wrp {
  position: relative;
  .Identification {
    display: block;
    width: 4px;
    height: 4px;
    background: #ff0000;
    position: absolute;
    top: 0;
    right: 6px;
    border-radius: 100%;
  }
}
</style>
